package com.cn.aam.checaiduo.ui.me;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Environment;
import android.support.v4.view.ViewPager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cn.aam.checaiduo.R;
import com.cn.aam.checaiduo.base.BaseActivity;
import com.cn.aam.checaiduo.base.ToolBarManager;
import com.cn.aam.checaiduo.utils.IntentUtils;
import com.cn.aam.checaiduo.utils.WindowsUtils;
import com.cn.aam.checaiduo.widget.VerticalPdfView;
import com.cn.aam.checaiduo.widget.WMProgressBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;

import java.io.File;

import butterknife.BindView;
import es.voghdev.pdfviewpager.library.PDFViewPager;
import es.voghdev.pdfviewpager.library.adapter.PDFPagerAdapter;
import es.voghdev.pdfviewpager.library.adapter.PdfScale;
import okhttp3.Call;
import okhttp3.Response;


public class PDFViewActivity extends BaseActivity {
    private final static String DATA_PDF_TITLE = "data_pdf_title";
    private final static String DATA_PDF_URL = "data_pdf_url";

    private final String pdfSaveDir = Environment.getExternalStorageDirectory().getPath() + "/pdf";


    @BindView(R.id.container)
    LinearLayout container;


    @BindView(R.id.pdfViewPager)
    VerticalPdfView mPager;
    @BindView(R.id.pdf_tv_curPage)
    TextView mCurPageCount;


    //model
    private String pdfTitle;
    private String pdfUrl;
    private String shareContent;


    //跳转
    public static Intent newIntent(Context context, String pdfTitle, String pdfUrl) {
        Intent i = new Intent(context, PDFViewActivity.class);
        i.putExtra(DATA_PDF_TITLE, pdfTitle);
        i.putExtra(DATA_PDF_URL, pdfUrl);
        return i;
    }


    @Override
    protected int layoutId() {
        return R.layout.activity_pdfview;
    }

    @Override
    protected void onGenerate() {
        initModel();
        initView();
        downLoadPdf();
    }


    private void initModel() {
        pdfTitle = getIntent().getStringExtra(DATA_PDF_TITLE);
        pdfUrl = getIntent().getStringExtra(DATA_PDF_URL);
        shareContent = getIntent().getStringExtra("shareContent");
    }

    @Override
    protected void initView() {
        ToolBarManager.with(this, WMContent).setBackground(R.color.toolbar_bg_grey)
                .setTitle(pdfTitle)
                .setTitleColor(R.color.toolbar_bg_grey)
                .setNavigationIcon(R.drawable.ic_nav_arrow_back);
    }


    /**
     * 下载pdf
     */
    private void downLoadPdf() {
        File dir = new File(pdfSaveDir);
        if (!dir.exists()) {
            dir.mkdir();
        }

        WMProgressBar.showProgressDialog(mContext, "加载中...");
        OkGo.get(pdfUrl)//
                .tag(this)//
                .execute(new FileCallback(dir.getPath(), "universalPdf.pdf") {  //文件下载时，可以指定下载的文件目录和文件名
                    @Override
                    public void onSuccess(File file, Call call, Response response) {
                        WMProgressBar.hideProgressDislog();
                        if (Build.VERSION.SDK_INT >= 21) {
                            openPdf(file);
                        } else {
                            startActivity(IntentUtils.openFile(file.getPath()));
                        }
                    }

                    @Override
                    public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                        //这里回调下载进度(该回调在主线程,可以直接更新ui)
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        WMProgressBar.hideProgressDislog();
                    }
                });
    }


    /**
     * 时间：2017/3/22 15:55
     * 描述：打开pdf
     */
    public void openPdf(File file) {
        PDFPagerAdapter adapter = new PDFPagerAdapter.Builder(this)
                .setPdfPath(file.getPath())
                .setScale(getPdfScale())
                .create();
        final int count = adapter.getCount();


        mCurPageCount.setText(1 + "/" + count);
        mPager.setAdapter(adapter);
        mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mCurPageCount.setText((position + 1) + "/" + count);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 时间：2017/3/23 10:35
     * 描述：设置pdf默认伸缩
     */
    private PdfScale getPdfScale() {
        PdfScale scale = new PdfScale();
        //伸缩倍数
        scale.setScale(1f);
        //伸缩中心
        scale.setCenterX(WindowsUtils.getScreenWidth(this) / 2);
        scale.setCenterY(WindowsUtils.getScreenHeight(this) / 2);
        return scale;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPager != null)
            ((PDFPagerAdapter) mPager.getAdapter()).close();

        File file = new File(pdfSaveDir, "universalPdf.pdf");
        if (file.exists()) {
            file.delete();
        }
    }


}
